package com.uchengwang.ui.cm_ui.me.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SwitchCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.uchengwang.R;
import com.uchengwang.functions.http.config.BaseConfig;
import com.uchengwang.functions.http.listener.OnHttpResultListener;
import com.uchengwang.functions.http.listener.OnHttpResultSingleListener;
import com.uchengwang.functions.http.listener.OnResultListener;
import com.uchengwang.functions.http.manager.OSSManager;
import com.uchengwang.functions.image.ImageManager;
import com.uchengwang.ui.UChengApplication;
import com.uchengwang.ui.base_ui.ui.BaseWithTitleActivity;
import com.uchengwang.ui.cm_ui.rychat.adapter.RyMemberAdapter;
import com.uchengwang.ui.cm_ui.cycle.bean.RyGroupBean;
import com.uchengwang.ui.cm_ui.rychat.bean.RyUserBean;
import com.uchengwang.ui.cm_ui.rychat.manager.RongChatManager;
import com.uchengwang.ui.cm_ui.rychat.manager.RyGroupManager;
import com.uchengwang.ui.cm_ui.rychat.msgtype.UcTypeMessage;
import com.uchengwang.ui.cm_ui.ucity.ui.ReportActivity;
import com.uchengwang.ui.utils.DialogUtils;
import com.uchengwang.ui.utils.LoadingUtils;
import com.uchengwang.ui.utils.UCommonUtil;

import java.util.ArrayList;
import java.util.List;

import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;


/**
 * Created by U城网 on 2017/6/27.
 * 群信息
 */

public class GroupInfoActivity extends BaseWithTitleActivity implements View.OnClickListener{
    private RecyclerView group_mem_rv;
    private SwitchCompat group_msg_bt, group_toTop_bt;//消息免打扰 置顶
    private RelativeLayout group_invite_rl, exchange_rl, group_mem_rl;//邀请好友
    private Button group_bt_exit;//退出群聊
    private RyMemberAdapter peoplesAdapter;
    private String groupName, groupDesc, groupLogo;
    private long ownerId ,groupId;//群主ID
    private AlertDialog dialog;

    private ImageView exchange_logo;//交流群logo
    private TextView exchange_name, exchange_desc;//交流群名称/描述
    private TextView group_invite_tv;//邀请群成员/推荐给好友
    private TextView group_myName, exchange_expire;//我的群昵称 交流群过期说明

    private RelativeLayout group_own_change, group_report, myName_rl, group_msg_rl;//转让管理权  举报 群昵称

    private boolean isOwner = false;//自己是不是群主
    private int groupType =-1;//群类型 1.Publish群; 2.好友群; 3.社团群; 4.兴趣群; 5.班级群; 6.纳新群  7是老乡群

    private boolean isInit = true;

    private RyGroupBean bean;
    private List<String> memmbers;
    public static boolean isDeleteMember = false;//是否移除了群成员

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_group_info);
        groupId = getIntent().getLongExtra(BaseConfig.ID, 0);
        setTitle("群设置");

        initView();
    }

    private void initView() {
        exchange_rl = (RelativeLayout) findViewById(R.id.group_exchange_rl);
        exchange_rl.setOnClickListener(this);

        exchange_name = (TextView) findViewById(R.id.group_exchange_name);
        exchange_logo = (ImageView) findViewById(R.id.group_exchange_logo);
        exchange_logo.setOnClickListener(this);
        exchange_desc = (TextView) findViewById(R.id.group_exchange_desc);


        group_mem_rv = (RecyclerView) findViewById(R.id.group_mem_rv);

        group_mem_rl = (RelativeLayout) findViewById(R.id.group_mem_rl);
        group_mem_rl.setOnClickListener(this);

        myName_rl = (RelativeLayout) findViewById(R.id.group_myName_rl);//群昵称
        myName_rl.setOnClickListener(this);

        group_myName = (TextView) findViewById(R.id.group_myName);//我的群昵称
        group_myName.setText(UChengApplication.nickName);

        group_msg_rl = (RelativeLayout) findViewById(R.id.group_msg_rl);//消息免打扰

        group_own_change = (RelativeLayout) findViewById(R.id.group_own_change);
        group_own_change.setOnClickListener(this);//管理群转让

        group_report = (RelativeLayout) findViewById(R.id.group_report);
        group_report.setOnClickListener(this);

        exchange_expire = (TextView) findViewById(R.id.group_exchange_expire);
        group_msg_bt = (SwitchCompat) findViewById(R.id.group_msg_bt);//消息免打扰


        group_msg_bt.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, final boolean b) {
                if (!isInit){
                    //消息免打扰
                    Conversation.ConversationNotificationStatus status = null;
                    if (b){
                        //打开消息免打扰
                        status = Conversation.ConversationNotificationStatus.DO_NOT_DISTURB;
                    }else {
                        status = Conversation.ConversationNotificationStatus.NOTIFY;
                    }
                    RongIM.getInstance().setConversationNotificationStatus(Conversation.ConversationType.GROUP, String.valueOf(groupId), status, new RongIMClient.ResultCallback<Conversation.ConversationNotificationStatus>() {
                        @Override
                        public void onSuccess(Conversation.ConversationNotificationStatus conversationNotificationStatus) {
                            UCommonUtil.getUtil().showToast(GroupInfoActivity.this, "设置成功");
                        }
                        @Override
                        public void onError(RongIMClient.ErrorCode errorCode) {
                            int code = errorCode.getValue();
                            String m = errorCode.getMessage();
                            Log.d("ryjjf", "免打扰="+code+"=m="+m);
                        }
                    });
                }else {
                    isInit = false;
                }
            }
        });

        group_invite_rl = (RelativeLayout) findViewById(R.id.group_invite_rl);
        group_invite_rl.setOnClickListener(this);//邀请好友入群
        group_invite_tv = (TextView) findViewById(R.id.group_invite_tv);

        group_bt_exit = (Button) findViewById(R.id.group_bt_exit);
        group_bt_exit.setOnClickListener(this);

        initData();

    }

    private void initData(){
        group_mem_rv.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        peoplesAdapter = new RyMemberAdapter(this);
        group_mem_rv.setAdapter(peoplesAdapter);

        getGroupInfo();
        getMembers();

        /**
         * 查询这个ID有没有在消息免打扰里
         * */
        RongIM.getInstance().getConversationNotificationStatus(Conversation.ConversationType.GROUP, String.valueOf(groupId), new RongIMClient.ResultCallback<Conversation.ConversationNotificationStatus>() {
            @Override
            public void onSuccess(Conversation.ConversationNotificationStatus s) {
                if (s == Conversation.ConversationNotificationStatus.DO_NOT_DISTURB){
                    //消息免打扰
                    group_msg_bt.setChecked(true);
                }else {
                    isInit = false;
                }
            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {

            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isDeleteMember){
            getGroupInfo();
            getMembers();
            isDeleteMember = false;
        }
    }



    /**
     * 调取环信的接口,获取群组信息
     * */
    private void getGroupInfo(){
        LoadingUtils.getUtils().loading(this);
        RyGroupManager.getManager().getGroupInfo(this, groupId, new OnHttpResultSingleListener<RyGroupBean>() {
            @Override
            public void onResult(int status, String msg, RyGroupBean groupBean) {
                LoadingUtils.getUtils().hide();
                if (groupBean != null){
                    bean = groupBean;

                    groupName = groupBean.getGroupName();
                    exchange_name.setText(groupName);
                    ownerId = groupBean.getAdminUid();//群管理员和群创建者不是一个概念
                    Log.d("hx", "群主="+ownerId);

                    if (ownerId == UCommonUtil.getUtil().getId()){
                        //说明自己是群主
                        group_bt_exit.setText("解散该群");

                        isOwner = true;
                        group_report.setVisibility(View.GONE);
                    }else {
                        //说明自己是群主
                        group_bt_exit.setText("退出该群");

                        isOwner = false;
                        group_report.setVisibility(View.VISIBLE);
                    }
                    groupLogo = groupBean.getGroupLogo();
                    groupDesc = groupBean.getGroupDesc();

                    if (!TextUtils.isEmpty(groupLogo)){
                        ImageManager.getInstance().loadImage(GroupInfoActivity.this, exchange_logo, groupLogo, ImageManager.ImageType.ROUND);
                    }else {
                        ImageManager.getInstance().loadImage(GroupInfoActivity.this, exchange_logo, R.drawable.default_image, ImageManager.ImageType.ROUND);
                    }

                    if (!TextUtils.isEmpty(groupDesc)){
                        exchange_desc.setText(groupDesc);
                    }else {
                        exchange_desc.setVisibility(View.GONE);
                    }
                    groupType = groupBean.getReferType();
                    switch (groupType){
                        //1.Publish群; 2.好友群; 3.社团群; 4.兴趣群; 5.班级群; 6.纳新群 7老乡群
                        case BaseConfig.GROUP_PUBLISG://U城报名临时群
                            //说明是临时交流群
                            exchange_expire.setVisibility(View.VISIBLE);
                            break;
                        case BaseConfig.GROUP_FRIEND://好友
                            group_invite_rl.setVisibility(View.VISIBLE);
                            break;
                        case BaseConfig.GROUP_CLUB://社团默认创建的群
                        case BaseConfig.GROUP_CLASS:
                            group_invite_rl.setVisibility(View.VISIBLE);
                            break;

                        case BaseConfig.GROUP_INTREST://兴趣群
                        case BaseConfig.GROUP_LX: //老乡群
                        case BaseConfig.GROUP_RECRUIT:
                            group_invite_rl.setVisibility(View.VISIBLE);

                            exchange_name.setText(groupName);
                            if (isOwner){
                                group_invite_tv.setText("邀请好友加入");
                            }else {
                                group_invite_tv.setText("推荐给好友");
                            }
                            break;
                    }

                    if (groupType != BaseConfig.GROUP_PUBLISG){
                        //活动报名群 不能转让管理权
                        if (isOwner){
                            //自己是群主
                            group_own_change.setVisibility(View.VISIBLE);
                        }else {
                            group_own_change.setVisibility(View.GONE);
                        }
                    }
                }
            }
        });


    }

    /**
     * 得到四个群成员信息
     * 写500 是因为出于下个界面会邀请人考虑
     * */
    private void getMembers(){
        RyGroupManager.getManager().getGroupMembers(this, groupId, 1, 500, new OnHttpResultListener<RyUserBean>() {
            @Override
            public void onResult(int status, String msg,  int total, List<RyUserBean> list) {
                if (list != null && list.size()>0){
                    int length = list.size();
                    if (length <4){
                        peoplesAdapter.setData(list);
                    }else {
                        List<RyUserBean> l = new ArrayList<RyUserBean>();
                        l.add(list.get(0));
                        l.add(list.get(1));
                        l.add(list.get(2));
                        l.add(list.get(3));
                        peoplesAdapter.setData(l);
                    }

                    //遍历将群成员ID拿出来
                    memmbers = new ArrayList<String>();
                    for (int i=0; i <length; i++){
                       memmbers.add(String.valueOf(list.get(i).getMemberUid()));
                    }
                }
            }
        });
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()){
//            case group_name_rl:
//                //群名称
//                Intent intent = new Intent(this, EditorInfoActivity.class);
//                intent.putExtra(BaseConfig.TYPE_STRING, groupName);
//                intent.putExtra(BaseConfig.TYPE, 15);
//                intent.putExtra(BaseConfig.ID, groupId);
//                startActivityForResult(intent, 0);
//                break;
            case R.id.group_exchange_logo://点击头像
                if (!TextUtils.isEmpty(groupLogo)){
                    List<String> l = new ArrayList<>();
                    l.add(groupLogo);
                    UCommonUtil.getUtil().startImagePagerActivity(this, OSSManager.OSS_HEAD, l, 0, false);
                }

                break;

            case R.id.group_exchange_rl://校吧交流群显示
                if (bean != null){
                    Intent i = new Intent(this, GroupInfoEditorActivity.class);
                    i.putExtra(BaseConfig.BEAN, bean);
                    startActivity(i);
                }else {
                    UCommonUtil.getUtil().showToast(this, "信息错误");
                }

                break;

            case R.id.group_mem_rl:
                //查看群成员
                Intent in = new Intent(this, MoreMemebersActivity.class);
                in.putExtra(BaseConfig.GROUP_ID, groupId);
                in.putExtra(BaseConfig.UID, ownerId);
                in.putExtra(BaseConfig.TYPE, 9);

                startActivity(in);
                break;

            case R.id.group_invite_rl:
                //邀请好友入群 1.Publish群; 2.好友群; 3.社团群; 4.兴趣群; 5.班级群; 6.纳新群 7老乡群
                switch (groupType){
                    case BaseConfig.GROUP_FRIEND:
                        invite();
                        break;
                    case BaseConfig.GROUP_INTREST:
                    case BaseConfig.GROUP_LX:
                        if (isOwner){
                            //是群主 邀请好友加入
                            invite();
                        }else {
                            //推荐给好友
                            if (bean != null){
                                UcTypeMessage message = (UcTypeMessage) RongChatManager.getUtils().createMsg(groupId, bean.getGroupName(), bean.getGroupDesc(), bean.getGroupLogo(), BaseConfig.GROUP_REMEND);
                                Intent intent1 = new Intent(this, FriendsActivity.class);
                                intent1.putExtra(BaseConfig.TYPE, 2);
                                intent1.putExtra(BaseConfig.GROUP_ID, groupId);
                                intent1.putExtra(BaseConfig.BEAN, message);
                                if (memmbers != null){
                                    intent1.putStringArrayListExtra(BaseConfig.MEMBERS, (ArrayList<String>) memmbers);
                                }
                                startActivity(intent1);
                            }
                        }
                        break;
                    case BaseConfig.GROUP_CLUB://默认创建的社团群 添加社团成员
                        Intent intent = new Intent(this, ClubMemberActivity.class);
                        intent.putExtra(BaseConfig.TYPE, 2);
                        intent.putExtra(BaseConfig.ORG_ID, UCommonUtil.getUtil().getId());
                        intent.putExtra(BaseConfig.GROUP_ID, groupId);
                        intent.putExtra(BaseConfig.GROUP_NAME_UCW, groupName);
                        startActivity(intent);
                        break;
                }
                break;

            case R.id.group_myName_rl:
                //我的群昵称
                break;

            case R.id.group_own_change:
                //管理权转让
                Intent intent2 = new Intent(this, MoreMemebersActivity.class);
                intent2.putExtra(BaseConfig.TYPE, 8);
                intent2.putExtra(BaseConfig.GROUP_ID, groupId);
                intent2.putExtra(BaseConfig.UID, ownerId);
                startActivity(intent2);
                break;

            case R.id.group_report:
                //举报
                Intent i = new Intent(this, ReportActivity.class);
                i.putExtra(BaseConfig.TYPE, BaseConfig.REPORT_GROUP_TYPE);
                i.putExtra(BaseConfig.GROUP_ID, groupId);
                startActivity(i);
                break;

            case R.id.group_bt_exit:
                //退出群聊
                String text = group_bt_exit.getText().toString();
                dialog = DialogUtils.getUtils().showDialogAll(this, false, "", "确定" + text + "?", "取消", "确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dialog.cancel();
                        if (ownerId == UCommonUtil.getUtil().getId()){
                            //解散该群
                            RyGroupManager.getManager().deleteGroup(GroupInfoActivity.this, UCommonUtil.getUtil().getId(), groupId, new OnResultListener() {
                                @Override
                                public void onResult(int stutas, String msg, int total, String data) {
                                    if (stutas != 0){
                                        UCommonUtil.getUtil().showToast(GroupInfoActivity.this, "解散失败");
                                    }else {
                                        UCommonUtil.getUtil().showToast(GroupInfoActivity.this, "解散成功");
                                        BaseConfig.changeGroup = true;//在我的界面更新群组数量
                                        BaseConfig.isRelease = true;
                                        GroupInfoActivity.this.finish();
                                    }
                                }
                            });
                        }else {
                            //退出群
                            RyGroupManager.getManager().exitGroup(GroupInfoActivity.this, true, groupId, 0, new OnResultListener() {
                                @Override
                                public void onResult(int stutas, String msg, int total, String data) {
                                    if (stutas ==0){
                                        UCommonUtil.getUtil().showToast(GroupInfoActivity.this, "退群成功");
                                        BaseConfig.changeGroup = true;//在我的界面更新群组数量
                                        BaseConfig.isRelease = true;
                                        GroupInfoActivity.this.finish();
                                    }else {
                                        UCommonUtil.getUtil().showToast(GroupInfoActivity.this, "退群失败");
                                    }
                                }
                            });
                        }
                        }
            }, null);
                break;
        }
    }

    /**
     * 邀请好友
     * */
    private void invite(){
        Intent intent = new Intent(this, FriendsActivity.class);
        intent.putExtra(BaseConfig.TYPE, 5);
        intent.putExtra(BaseConfig.GROUP_ID, groupId);
        intent.putExtra(BaseConfig.OWN_ID, ownerId);
        intent.putExtra(BaseConfig.GROUP_NAME, groupName);
        if (memmbers != null){
            intent.putStringArrayListExtra(BaseConfig.MEMBERS, (ArrayList<String>) memmbers);
        }
        startActivity(intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode ==1){
            String name = data.getStringExtra(BaseConfig.ORG_NAME);
            exchange_name.setText(name);

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        List<RyUserBean> users = peoplesAdapter.getData();
        users.clear();
        users = null;
    }

}
